package com.liu.tools;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class Net {

	private static Logger logger = Logger.getLogger(Net.class.getName());
	/**
	 * 
	 * @author huangxi
	 * @Description	发送请求报文,获取响应报文,使用POST方式
	 * @param urlStr 请求地址
	 * @param reqData post过去的请求报文
	 * @return 服务端响应报文
	 */
	public static String sendRequestAndGetResponse(String urlStr, String reqData) {
		OutputStream os = null;
		InputStream is = null;
		URL url = null;
		try {
			url = new URL(urlStr);
		} catch (MalformedURLException e) {
			logger.error("url error:" + url, e);
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.setDoOutput(true);
			connection.setRequestProperty("Content-Length", "64");
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			os = connection.getOutputStream();
		} catch (IOException e) {
			logger.error("io error :", e);
		}

		logger.info("params:" + reqData);
		PrintWriter outPrintWriter = new PrintWriter(os);
		outPrintWriter.print(reqData);
		outPrintWriter.flush();

		try {
			if (os != null) {
				os.close();
			}
			is = connection.getInputStream();
		} catch (IOException e) {
			logger.error("io error :", e);
		}
		logger.info("send request ok");
		return getResponseFromServer(is);
	}
	
	/**
	 * 
	 * @author huangxi
	 * @Description	发送请求报文,获取响应报文,使用POST方式
	 * @param urlStr 请求地址
	 * @param reqData post过去的请求报文
	 * @return 服务端响应报文
	 */
	 public static String sendGet(String url, String param) {
	        String result = "";
	        BufferedReader in = null;
	        try {
	            String urlNameString = url + "?" + param;
	            URL realUrl = new URL(urlNameString);
	            // 打开和URL之间的连接
	            URLConnection connection = realUrl.openConnection();
	            // 设置通用的请求属性
	            connection.setRequestProperty("accept", "*/*");
	            connection.setRequestProperty("connection", "Keep-Alive");
	            connection.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 建立实际的连接
	            connection.connect();
	            // 获取所有响应头字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍历所有的响应头字段
	            for (@SuppressWarnings("unused") String key : map.keySet()) {
	               // System.out.println(key + "--->" + map.get(key));
	            }
	            // 定义 BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送GET请求出现异常！" + e);
	            e.printStackTrace();
	        }
	        // 使用finally块来关闭输入流
	        finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	        return result;
	    }
	
	/**
	 * 
	 * @author huangxi
	 * @Description 从服务端获取输入流,打印传过来的响应报文.
	 * @return 响应报文的字符串
	 */
	public static String getResponseFromServer(InputStream inputStream) {
		String resp = null;
		byte[] data = new byte[4096];
		ByteArrayOutputStream baos = null;
		try {
			 baos = new ByteArrayOutputStream();
			int i = 0;
			logger.info("read Response");
			while ((i = inputStream.read(data)) != -1) {
				baos.write(data, 0, i);
			}
			resp = new String(baos.toByteArray(), "utf-8");
			logger.debug(resp);
			
		} catch (IOException e) {
			logger.error("io error :", e);
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					logger.error("io error :", e);
				}
				baos = null;
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					logger.error("io error :", e);
				}
				inputStream = null;
			}
		}
		return resp;
	}

}
